from PyQt6.QtWidgets import (QWidget, QLabel, QPushButton, QVBoxLayout, 
                            QHBoxLayout, QDialog, QColorDialog, QSpinBox,
                            QFormLayout, QGroupBox)
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QColor
import json

class TranslationDisplay(QWidget):
    moved = pyqtSignal()  # 添加移动信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowFlags(
            Qt.WindowType.FramelessWindowHint | 
            Qt.WindowType.WindowStaysOnTopHint |
            Qt.WindowType.Tool
        )
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
        # 创建主布局
        self.main_layout = QVBoxLayout(self)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(0)  # 设置布局间距为0
        
        # 创建顶部工具栏
        self.toolbar = QWidget()
        self.toolbar.setFixedHeight(20)
        self.toolbar.setStyleSheet("""
            QWidget {
                background-color: transparent;
            }
        """)
        
        # 创建工具栏布局
        toolbar_layout = QHBoxLayout(self.toolbar)
        toolbar_layout.setContentsMargins(0, 0, 0, 0)
        toolbar_layout.setSpacing(2)
        
        # 按钮基础样式
        button_style = """
            QPushButton {
                background-color: transparent;
                color: #808080;
                border: none;
                font-size: 14px;
                font-family: "Microsoft YaHei UI";
            }
            QPushButton:hover {
                background-color: rgba(128, 128, 128, 0.2);
                border-radius: 2px;
            }
        """
        
        # 创建设置按钮
        self.settings_btn = QPushButton("⚙")
        self.settings_btn.setFixedSize(20, 20)
        self.settings_btn.setStyleSheet(button_style)
        self.settings_btn.clicked.connect(self.show_settings)
        
        # 创建关闭按钮
        self.close_btn = QPushButton("×")
        self.close_btn.setFixedSize(20, 20)
        self.close_btn.setStyleSheet(button_style)
        self.close_btn.clicked.connect(self.close)
        
        # 添加按钮到工具栏
        toolbar_layout.addStretch()
        toolbar_layout.addWidget(self.settings_btn)
        toolbar_layout.addWidget(self.close_btn)
        
        # 创建标签
        self.label = QLabel()
        self.label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        self.label.setWordWrap(True)
        self.label.setStyleSheet("""
            QLabel {
                background-color: rgba(0, 0, 0, 0.7);
                color: white;
                border-radius: 4px;
                padding: 10px;
                font-family: "Microsoft YaHei UI";
                margin: 0px;  /* 移除外边距 */
            }
        """)
        
        # 添加组件到主布局
        self.main_layout.addWidget(self.toolbar)
        self.main_layout.addWidget(self.label)
        
        # 拖动相关变量
        self.dragging = False
        self.drag_position = None
        
        # 加载保存的样式
        self.load_style_settings()
        
    def load_style_settings(self):
        """加载保存的样式设置"""
        try:
            with open('translation_style.json', 'r') as f:
                style = json.load(f)
                self.update_style(
                    style.get('font_color', '#FFFFFF'),
                    style.get('background_color', 'rgba(0, 0, 0, 0.7)'),
                    style.get('font_size', 14)
                )
        except:
            pass
            
    def save_style_settings(self, font_color, background_color, font_size):
        """保存样式设置"""
        try:
            with open('translation_style.json', 'w') as f:
                json.dump({
                    'font_color': font_color,
                    'background_color': background_color,
                    'font_size': font_size
                }, f)
        except:
            pass
            
    def update_style(self, font_color, background_color, font_size):
        """更新显示样式"""
        self.label.setStyleSheet(f"""
            QLabel {{
                background-color: {background_color};
                color: {font_color};
                border-radius: 4px;
                padding: 10px;
                font-family: "Microsoft YaHei UI";
                font-size: {font_size}px;
                margin: 0px;  /* 移除外边距 */
            }}
        """)
        
    def show_settings(self):
        """显示设置对话框"""
        dialog = QDialog(self)
        dialog.setWindowFlags(
            dialog.windowFlags() | 
            Qt.WindowType.WindowStaysOnTopHint
        )
        dialog.setWindowTitle("显示设置")
        dialog.setModal(True)
        dialog.setMinimumWidth(400)
        
        # 设置对话框样式
        dialog.setStyleSheet("""
            QDialog {
                background-color: #f5f5f5;
            }
            QLabel {
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                color: #333333;
            }
            QSpinBox {
                padding: 6px;
                border: 1px solid #E0E0E0;
                border-radius: 4px;
                background-color: white;
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                min-width: 80px;
            }
            QSpinBox:focus {
                border-color: #0078D4;
            }
            QPushButton {
                background-color: #0078D4;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #106EBE;
            }
            QPushButton:pressed {
                background-color: #005A9E;
            }
            QGroupBox {
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                border: 1px solid #E0E0E0;
                border-radius: 4px;
                margin-top: 12px;
                padding-top: 16px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                color: #333333;
            }
        """)
        
        # 创建主布局
        layout = QVBoxLayout()
        layout.setSpacing(10)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 创建字体设置组
        font_group = QGroupBox("字体设置")
        font_layout = QFormLayout()
        font_layout.setSpacing(10)
        font_layout.setContentsMargins(15, 15, 15, 15)
        
        # 字体大小设置
        font_size_spin = QSpinBox()
        font_size_spin.setRange(8, 72)
        current_style = self.label.styleSheet()
        font_size = 14
        if 'font-size:' in current_style:
            try:
                font_size = int(current_style.split('font-size:')[1].split('px')[0].strip())
            except:
                pass
        font_size_spin.setValue(font_size)
        
        # 创建字体大小设置的布局
        font_size_layout = QHBoxLayout()
        font_size_layout.addWidget(QLabel("字体大小:"))
        font_size_layout.addWidget(font_size_spin)
        font_size_btn = QPushButton("应用")
        font_size_btn.clicked.connect(lambda: self.save_font_size(font_size_spin.value()))
        font_size_layout.addWidget(font_size_btn)
        font_layout.addRow(font_size_layout)
        
        # 字体颜色设置
        font_color_btn = QPushButton()
        font_color_btn.setStyleSheet(f"background-color: {self.label.palette().color(self.label.foregroundRole()).name()};")
        font_color_btn.clicked.connect(lambda: self.choose_color(font_color_btn, False))
        font_layout.addRow("字体颜色:", font_color_btn)
        
        font_group.setLayout(font_layout)
        
        # 创建背景设置组
        bg_group = QGroupBox("背景设置")
        bg_layout = QFormLayout()
        bg_layout.setSpacing(10)
        bg_layout.setContentsMargins(15, 15, 15, 15)
        
        # 背景颜色设置
        bg_color_btn = QPushButton()
        bg_color_btn.setStyleSheet(f"background-color: {self.label.palette().color(self.label.backgroundRole()).name()};")
        bg_color_btn.clicked.connect(lambda: self.choose_color(bg_color_btn, True))
        bg_layout.addRow("背景颜色:", bg_color_btn)
        
        bg_group.setLayout(bg_layout)
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        # 确定按钮
        ok_btn = QPushButton("确定")
        ok_btn.clicked.connect(lambda: self.save_settings(
            font_color_btn.styleSheet().split(":")[1].strip(),
            bg_color_btn.styleSheet().split(":")[1].strip(),
            font_size_spin.value(),
            dialog
        ))
        
        # 取消按钮
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(dialog.reject)
        
        button_layout.addStretch()
        button_layout.addWidget(ok_btn)
        button_layout.addWidget(cancel_btn)
        
        # 添加所有组件到主布局
        layout.addWidget(font_group)
        layout.addWidget(bg_group)
        layout.addLayout(button_layout)
        
        dialog.setLayout(layout)
        dialog.exec()
        
    def choose_color(self, button, with_alpha=False):
        """选择颜色"""
        current_style = button.styleSheet()
        current_color = current_style.split(":")[1].strip()
        
        color_dialog = QColorDialog()
        color_dialog.setWindowFlags(
            color_dialog.windowFlags() | 
            Qt.WindowType.WindowStaysOnTopHint
        )
        color_dialog.setOption(QColorDialog.ColorDialogOption.ShowAlphaChannel, with_alpha)
        
        if current_color.startswith('rgba'):
            rgba = current_color.strip('rgba()').split(',')
            rgba = [x.strip().rstrip(');') for x in rgba]
            color = QColor(int(rgba[0]), int(rgba[1]), int(rgba[2]), int(float(rgba[3]) * 255))
        else:
            color = QColor(current_color)
        
        color_dialog.setCurrentColor(color)
        
        if color_dialog.exec() == QDialog.DialogCode.Accepted:
            color = color_dialog.currentColor()
            if with_alpha:
                button.setStyleSheet(f"background-color: rgba({color.red()}, {color.green()}, {color.blue()}, {color.alpha()/255.0});")
            else:
                button.setStyleSheet(f"background-color: {color.name()};")
            
    def save_font_size(self, font_size):
        """保存字体大小设置"""
        current_style = self.label.styleSheet()
        current_bg_color = self.label.palette().color(self.label.backgroundRole()).name()
        current_font_color = self.label.palette().color(self.label.foregroundRole()).name()
        
        style = f"""
            QLabel {{
                background-color: {current_bg_color};
                color: {current_font_color};
                border-radius: 4px;
                padding: 10px;
                font-family: "Microsoft YaHei UI";
                font-size: {font_size}px;
            }}
        """
        self.label.setStyleSheet(style)
        
    def save_settings(self, font_color, bg_color, font_size, dialog):
        """保存所有设置"""
        self.update_style(font_color, bg_color, font_size)
        self.save_style_settings(font_color, bg_color, font_size)
        dialog.accept()
        
    def update_size(self, width, height):
        """更新窗口大小"""
        # 确保宽度与检测区域宽度完全一致
        self.setFixedWidth(width)
        # 高度将根据内容动态调整，不再设置固定高度
        
    def setText(self, text):
        """设置显示文本"""
        self.label.setText(text)
        # 先设置标签宽度为窗口宽度
        self.label.setFixedWidth(self.width())
        # 让QLabel根据内容和宽度自动调整高度
        self.label.adjustSize()
        # 重新获取sizeHint高度，确保内容完整展示
        label_height = self.label.sizeHint().height()
        toolbar_height = self.toolbar.height()
        margins = self.main_layout.contentsMargins()
        new_height = label_height + toolbar_height + margins.top() + margins.bottom()
        self.setFixedHeight(new_height)
        
    def mousePressEvent(self, event):
        """鼠标按下事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.dragging = True
            self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()
            
    def mouseMoveEvent(self, event):
        """鼠标移动事件"""
        if self.dragging and event.buttons() & Qt.MouseButton.LeftButton:
            # 使用setGeometry而不是move，减少重绘
            new_pos = event.globalPosition().toPoint() - self.drag_position
            self.setGeometry(new_pos.x(), new_pos.y(), self.width(), self.height())
            self.moved.emit()  # 发出移动信号
            event.accept()
            
    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.dragging = False
            # 在拖动结束后进行一次完整的重绘
            self.update()
            event.accept() 